/**
 * 
 */
package com.xbjtech.controller;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.excel.poi.util.PoiAnalyticalData;
import com.excel.poi.util.PoiUtil;
import com.github.pagehelper.PageInfo;
import com.xbjtech.model.Order;
import com.xbjtech.model.OrderExample;
import com.xbjtech.model.OrderExample.Criteria;
import com.xbjtech.model.vo.QueryVO;
import com.xbjtech.service.OrderService;
import com.xbjtech.util.ResponseBean;
import com.xbjtech.xls.ExcelInputModel;
import com.xbjtech.xls.ExcelOutputModel;

import lombok.extern.slf4j.Slf4j;

@Controller
@RequestMapping("/order")
@Slf4j
public class OrderController {
	
	@Autowired
	OrderService orderService;
	
	@GetMapping("/list")
	public String list(Model model) {
		return "order/list";
	}
	
	@RequestMapping("/page")
	@ResponseBody
	public Map<String, Object> page(
			QueryVO queryVO,
			@RequestParam(required = false, defaultValue = "1") Integer page, 
			@RequestParam(required = false, defaultValue = "10")Integer rows) {
		log.info("queryVO:{}", queryVO);
		OrderExample example = new OrderExample();
		example.setOrderByClause("id desc");
		Criteria criteria = example.createCriteria();
		if (null != queryVO.getAjOrderId() && !queryVO.getAjOrderId().isEmpty()) {
			criteria.andAjOrderIdEqualTo(queryVO.getAjOrderId());
		}
		if (null != queryVO.getMobile() && !queryVO.getMobile().isEmpty()) {
			criteria.andBuyerMobileLike("%" + queryVO.getMobile() + "%");
		}
		if (null != queryVO.getStoreId()) {
			criteria.andBusinessIdEqualTo(queryVO.getStoreId());
		}
		if (null != queryVO.getBeginTime()) {
			criteria.andCreateTimeGreaterThanOrEqualTo(queryVO.getBeginTime());
		}
		if (null != queryVO.getEndTime()) {
			criteria.andCreateTimeLessThan(new Date(queryVO.getEndTime().getTime() + 24 * 60 * 60 * 1000));
		}
		List<Order> list = orderService.list(example, page, rows);
		PageInfo<Order> pageInfo = new PageInfo<>(list);
		Map<String, Object> map = new HashMap<>();
		map.put("total", pageInfo.getTotal());
		map.put("rows", pageInfo.getList());
		
		return map;
	}
	
	@PostMapping("/save")
	@ResponseBody
	public ResponseBean save(Order order) {
		log.info("order:{}", order);
		try {
			if (order.getId() == null) {
				order.setCreateTime(new Date());
				order.setStatus(1);
				orderService.insertOrder(order);
				return new ResponseBean(true, "保存成功");
			} else {
				orderService.updateOrder(order);
				return new ResponseBean(true, "更新成功");
			}
		} catch (Exception e) {
			log.error("OrderController.save() throws a exception -> {}", e.getMessage());
		}
		return new ResponseBean(false, "操作失败");
	}
	
	@PostMapping("/del")
	@ResponseBody
	public ResponseBean save(Long id) {
		try {
			orderService.deleteOrderById(id);
			return new ResponseBean(true, "删除成功");
		} catch (Exception e) {
			log.error("{}", e.getMessage());
		}
		return new ResponseBean(false, "删除失败");
	}
	
	@PostMapping("/exceloutput")
	public void excelOutput(QueryVO queryVO, HttpServletResponse response) {
		OrderExample example = new OrderExample();
		example.setOrderByClause("id desc");
		Criteria criteria = example.createCriteria();
		if (null != queryVO.getAjOrderId() && !queryVO.getAjOrderId().isEmpty()) {
			criteria.andAjOrderIdEqualTo(queryVO.getAjOrderId());
		}
		if (null != queryVO.getMobile() && !queryVO.getMobile().isEmpty()) {
			criteria.andBuyerMobileLike("%" + queryVO.getMobile() + "%");
		}
		if (null != queryVO.getStoreId()) {
			criteria.andBusinessIdEqualTo(queryVO.getStoreId());
		}
		if (null != queryVO.getBeginTime()) {
			criteria.andCreateTimeGreaterThanOrEqualTo(queryVO.getBeginTime());
		}
		if (null != queryVO.getEndTime()) {
			criteria.andCreateTimeLessThan(new Date(queryVO.getEndTime().getTime() + 24 * 60 * 60 * 1000));
		}
		// 这一块具体项目具体对待
		List<Order> list = orderService.list(example, 1, 10000);
		
		Collection<Object> col = new ArrayList<Object>();
		for (Order o : list) {
			ExcelOutputModel model = new ExcelOutputModel();
			model.setAjOrderId(o.getAjOrderId());
			model.setBuyerName(o.getBuyerName());
			model.setBuyerMobile(o.getBuyerMobile());
			model.setBuyerAddress(o.getBuyerAddress());
			col.add(model);
		}
		try {
			response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
			response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("工单.xlsx", "UTF-8"));
			ServletOutputStream outputStream = response.getOutputStream();
			XSSFWorkbook xlsx = PoiUtil.createXSSFWorkbook("工单", ExcelOutputModel.class, col);
			xlsx.write(outputStream);
			outputStream.flush();
		} catch (IllegalArgumentException | IllegalAccessException | InstantiationException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	
	@PostMapping("/excelinput")
	public String excelInput(Long businessId, MultipartFile file, RedirectAttributes redirectAttributes) {
		// 导入数据
		log.info("businessId:{},file:{}", businessId, file);
		//file --> XSSFWorkBook
		try {
			XSSFWorkbook xlsx = new XSSFWorkbook(file.getInputStream());
			List<Object> rows = PoiAnalyticalData.AnalyticPoiExcel(xlsx, ExcelInputModel.class);
			// List<Object> --> List<Order>
			List<Order> orders = new LinkedList<>();
			for (Object o : rows) {
				ExcelInputModel m = (ExcelInputModel) o;
				Order order = new Order();
				order.setAjOrderId(m.getAjOrderId());
				order.setBusinessId(businessId);
				order.setBuyerName(m.getBuyerName());
				order.setBuyerMobile(m.getBuyerMobile());
				order.setBuyerAddress(m.getBuyerAddress());
				order.setBuyerProduct(m.getBuyerProduct());
				order.setBuyerRemark(m.getBuyerRemark());
				order.setBuyerCar(m.getBuyerCar());
				order.setCreateTime(new Date());
				order.setStatus(1);
				orders.add(order);
			}
			orderService.save(orders);
			// 导入成功
			redirectAttributes.addFlashAttribute("successMessage", "导入成功");
		} catch (Exception e) {
			e.printStackTrace();
			redirectAttributes.addFlashAttribute("errorMessage", "导入失败");
		}
		return "redirect:/order/list";
	}
	
}
